package com.goodluck.goodluckim.network;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.goodluck.goodluckim.sdk.LogUtils;
import com.goodluck.goodluckim.utils.AndroidUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * Created by wyj on 2018/9/10.
 */

public class WebSocketService extends Service implements WebSocketListener {

    private static final long HEART_TIME = 30000;
    /**
     * 网络监测
     */
    private NetworkReceiver mReceiver;
    /**
     * 心跳包线程池
     */
    private ScheduledExecutorService mHeartExecutorService;

    /**
     * 监听网络状态广播
     */
    private class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) {
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    WebSocketClient.getInstance().connect();
                    LogUtils.printe("Socket断网重连");
                }
            }
        }
    }

    @Override
    public void onServiceStatusConnectChanged(int statusCode) {
        switch (statusCode) {
            case WebSocketListener.STATUS_CONNECT_SUCCESS:
                startHeart();
                break;
            case WebSocketListener.STATUS_CONNECT_CLOSED:
                stopHeart();
                WebSocketClient.getInstance().disconnect();
                break;
            case WebSocketListener.STATUS_CONNECT_ERROR:
                stopHeart();
                WebSocketClient.getInstance().connect();
                break;
            default:

                break;
        }
    }

    @Override
    public void onMessageReceived(String message) {
        WebSocketClient.getInstance().reponse();
        if (TextUtils.isEmpty(message)) {
            return;
        }
        WebSocketDispatcher.getInstance().dispatcher(message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mReceiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        WebSocketClient.getInstance().setListener(this);
        WebSocketClient.getInstance().connect();
        LogUtils.printe("Socket初始连接");
        return START_NOT_STICKY;
    }

    /**
     * 启动心跳包
     */
    public void startHeart() {
        if (mHeartExecutorService == null) {
            mHeartExecutorService = Executors.newSingleThreadScheduledExecutor();
            mHeartExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    WebSocketClient.getInstance().request("PING").addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) {
                            if (future.isSuccess()) {
                                LogUtils.printe("心跳包发送成功");
                            } else {
                                LogUtils.printe("心跳包发送失败");
                            }
                        }
                    });
                }
            }, 0, HEART_TIME, TimeUnit.MILLISECONDS);
        }
    }

    /**
     * 停止心跳包
     */
    public void stopHeart() {
        if (mHeartExecutorService != null) {
            mHeartExecutorService.shutdownNow();
            mHeartExecutorService = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        stopHeart();
        WebSocketClient.getInstance().reponse();
        WebSocketClient.getInstance().disconnect();

        /**
         * 重启服务
         */
        if (AndroidUtils.isTaskRunning(this, getPackageName())) {
            startService(new Intent(this, WebSocketService.class));
        }
    }
}
